<!--
 * @Author: 黄宇/Hyuishine
 * @Date: 2022-05-24 17:36:10
 * @LastEditors: 黄宇/Hyuishine
 * @LastEditTime: 2024-05-16 15:08:11
 * @Description: 
 * @Email: hyuishine@gmail.com
 * @Company: 3xData
 * @youWant: add you want
-->
<template>
  <view class="container_page">

    <!-- 顶部自定义导航栏 -->
    <action-bar :options="navOptions" />

    <view class="scrollPane" :style="contentHeight">

      <uni-section :title="task.wbName" type="line" v-for="task, i in taskData" :key="i">
        <view class="formItem">
          <view class="label">执业人员</view>
          <view @click="openModal(i)">
            <view v-if="task.selectList.length == 0">分配执业人员</view>
            <view v-else>
              <view class="flex flex-direction" v-for="(list, index) in getSelectList(task.selectList)" :key="index">
                {{ list }}
              </view>
            </view>
          </view>
        </view>
      </uni-section>
      <!-- <view class="bar" :class="{ selecting: status }" v-for="task, i in taskData" :key="i" @click="changeValue(i)">
        <view class="title">{{ task.wbName }}</view>
        <view class="container_fold">
          <view class="formItem justify-between" style="height: auto; align-items: flex-start">
            <view class="label">执业人员</view>
            <view @click="openModal">
              <view v-if="task.selectList.length == 0">分配执业人员</view>
              <view v-else>
                <view class="flex flex-direction" v-for="(list, index) in getSelectList(task.selectList)" :key="index">
                  {{ list }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view> -->
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer">
      <button class="btn_submit" :disabled="disabled" @click="submit()">确定</button>
    </view>

    <select-modal :modalName="modalName" @close="closeModal" :list="cloneList" @submit="confirm"></select-modal>
  </view>
</template>
<script>
let _ = require('lodash')
import selectModal from '../../../components/select-modal/select-modal.vue'
export default {
  components: { selectModal },
  data() {
    return {
      modalName: null,

      status: false,
      navOptions: {
        left: {
          icon: 'back'
        },
        center: {
          title: "任务分配具体负责人"
        }
      },
      taskData: [], // 维保列表
      peopleList: [], // 人员列表
      projectId: null, // 项目id
      index: "", // 索引值
      staffIdList: [], // 所有的执行人员名单

      disabled: false, // 当为true时，代表内容不合规，无法提交请求
      newTaskData: [], // 存储选中的执业人员列表信息

      cloneList: [],// 深克隆一个新数组，用于存放人员列表，防止源数据污染
      loading: false,
    }
  },
  destroyed() {
    //! 离开当前页面时，需要清空已分配人员信息，否则，在下一次分配人员时，之前分配的东西都回显回来了
    this.$store.state.task.taskData = []
  },
  onLoad(options) {
    let that = this
    this.taskData = []
    this.projectId = options?.projectId
    if (this.projectId) {
      // this.taskData = this.$store.state.task.wbList
      // 获取执业人员列表
      this.getPeopleList()

    } else {
      uni.showToast({
        title: `系统错误`,
        icon: "none",
      });
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        });
      }, 1000);
    }

  },
  methods: {
    // 保存
    submit() {
      new Promise((resolve, reject) => {
        let newTaskData = []
        this.taskData.forEach(item => {
          item.staffId = []
          item.staffId = item.selectList.map(k => k.staffId)
        })
        console.log(this.taskData, this.peopleList)
        for (let i = 0; i < this.taskData.length; i++) {
          this.$set(newTaskData, i, [])
          for (let j = 0; j < this.taskData[i].staffId.length; j++) {
            for (let k = 0; k < this.peopleList.length; k++) {
              if (this.peopleList[k].staffId == this.taskData[i].staffId[j]) {
                newTaskData[i].push(this.peopleList[k].facilityOperators || (this.peopleList[k].isProjectHead == '1' ? '是' : '否'))
              }
            }
          }
        }
        resolve(newTaskData)
      }).then(res => {
        console.log(res)
        for (let a = 0; a < res.length; a++) {
          if (res[a].indexOf('2') == '-1' && res[a].indexOf('3') == '-1' &&
            res[a].indexOf("是") == "-1") {
            uni.showToast({
              title: `选择的执业人员中无中级及中级以上人员或者项目负责人，无法进行保存操作！`,
              icon: "none",
            });
            this.disabled = true
            break;
          } else {
            this.disabled = false
          }
        }
        return this.disabled
      }).then(res => {
        // 当res为false时，代表所有数据填报正常，反之则有误
        if (!res) {
          this.$store.commit("setTaskData", this.taskData)
          let platform = uni.getSystemInfoSync().platform
          if (platform == 'ios' || platform == 'devtools') {
            uni.navigateBack({
              success: () => {
                const pages = getCurrentPages();
                //! 在真机调试时，这里必须得是-2，但是在微信开发工具上时必须得是-1 ，问题暂不知，切记切记
                const prevPage = pages[pages.length - 2];
                prevPage.$vm.getWbList(this.taskData); // 调用上一个页面的方法 getProjectInfo
              }
            });
          } else if (platform == 'android') {
            uni.navigateBack({
              success: () => {
                const pages = getCurrentPages();
                //! 在真机调试时，这里必须得是-2，但是在微信开发工具上时必须得是-1 ，问题暂不知，切记切记
                const prevPage = pages[pages.length - 2];
                prevPage.$vm.getWbList(this.taskData); // 调用上一个页面的方法 getProjectInfo
              }
            });
          }
        } else {
          this.disabled = false
        }
      })
    },
    // 获取索引值
    changeValue(index) {
      console.log(index)
      this.index = index
    },
    // 执业人员change
    practChange(val) {
      this.taskData[this.index].staffId = val
    },
    // 打开模态框
    openModal(i) {
      this.index = i
      let peopleList = _.cloneDeep(this.peopleList)
      // 待审核状态
      let ToExamined = {
        checked: false, // 是否选中
        active: true, // 是否不允许切换选中效果
        tips: '待审核'
      }
      this.cloneList = this.getState(peopleList)
      this.modalName = 'bottomModal'
    },

    // 追加字段用于判断按钮是否允许切换点击、展示原因、是否点击等操作
    getState(peopleList) {
      // 待审核状态
      let ToExamined = {
        checked: false, // 是否选中
        active: true, // 是否不允许切换选中效果
        tips: '待审核'
      }
      let list = peopleList.map(item => {
        let tip = item.certificateName
        // if (item.hasOwnProperty('facilityOperatorsName') && item.hasOwnProperty('registeredFireEngineerName')) {
        //   tip = item.facilityOperatorsName + ',' + item.registeredFireEngineerName
        // } else if (item.hasOwnProperty('registeredFireEngineerName')) {
        //   tip = item.registeredFireEngineerName
        // } else if (item.hasOwnProperty('facilityOperatorsName')) {
        //   tip = item.facilityOperatorsName
        // }
        // 已审核状态
        let Audited = {
          checked: false,
          active: false,
          tips: tip
        }
        // 离职状态
        let depAudited = {
          checked: false,
          active: true,
          tips: '离职'
        }
        // 已删除状态
        let depAudited1 = {
          checked: false,
          active: true,
          tips: '已删除'
        }
        // 同步web端需求，当该执业人员的approveState状态为0时代表未审核，不允许选中
        if (item.approveState == "0") {
          Object.assign(item, ToExamined)
        } else {
          if (item.state == '1') {
            // Object.assign(item, Audited)
            if (item.projectStaffDelFlag == '0') {
              Object.assign(item, Audited)
            } else {
              Object.assign(item, depAudited1)
            }
          } else {
            Object.assign(item, depAudited)
          }
        }
        return item
      })
      return list
    },

    // 关闭模态框
    closeModal(e) {
      this.modalName = e
    },
    confirm(e) {
      this.modalName = null
      // 创建一个字段存放匹配条件成功的数据
      let oldlist = e.filter(item => {
        if (item.checked) {
          return item
        }
      })
      this.taskData[this.index].selectList = oldlist
      // 判断选中的数据是否满足至少一个中级及中级以上的执业人员
      let newList = oldlist.filter(item => {
        if ((item.facilityOperators.indexOf('2') != '-1' || item.facilityOperators.indexOf('3') != '-1' || item.isProjectHead.indexOf('1') != '-1')) {
          return item
        }
      })
      if (newList.length == 0 && oldlist.length != 0) {
        uni.showToast({
          title: `选择的执业人员中无中级及中级以上人员或者项目负责人，无法进行保存操作！`,
          icon: "none",
        });
      }
    },
    // 获取执业列表
    getPeopleList() {
      if (this.loading) return

      this.loading = true
      uni.showLoading({
        title: '正在加载请稍后',
        mask: true
      });
      let dist = {
        pageSize: '-1',
        pageNo: '-1',
        projectId: this.projectId
      }
      this.$store.dispatch('wbPeopleList', dist).then(res => {
        if (res && res.code === 200) {
          this.peopleList = res.data.items
          if (this.$store.state.task.taskData.length != 0) {
            this.echoMaintenance()
          } else {
            this.getMaintenance()
          }
        }
      }).finally(() => {
          this.loading = false
          uni.hideLoading();
      })
    },
    // 回显数据
    echoMaintenance() {
      let that = this
      let taskData = this.$store.state.task.taskData
      let dist = {
        selectList: []
      }
      taskData.map(item => {
        return Object.assign(item, dist)
      })
      taskData.map((taskDist, index) => {
        let newList = []
        try {
          taskDist.staffId.forEach(item => {
            that.peopleList.forEach(list => {
              if (list.staffId == item) {
                newList.push(list)
              }
            })
          })
        } catch (e) {

        }
        taskData[index].selectList = newList
      })
      this.taskData = taskData
    },
    getMaintenance() {
      this.$store.dispatch("wbList", this.projectId).then(({
        data
      }) => {
        let dist = {
          staffId: [],
          selectList: []
        }
        data.forEach(item => {
          Object.assign(item, dist)
        })
        this.taskData = data
        console.log(this.taskData)
      })
    },
    // 获取选中的执业人员回显
    getSelectList(list) {
      if (list.length != 0) {
        return list.map(item => item.name)
      }
      return
    }
  },
  computed: {
    // 内容页的 最小高度 100vh - 顶部自定义标题栏 - 底部提交按钮
    contentHeight() {
      // 顶部自定义导航栏高度
      const actionBarHeight = uni.getStorageSync("menuInfo").actionBarHeight || 40
      return 'height:calc(100vh - ' + (actionBarHeight + 65) + 'px);'
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

::v-deep .uni-section {
  margin-top: 0;
  background-color: transparent;
}

.container_page {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: #eff1f7;

  .scrollPane {
    overflow-y: auto;

    .formItem {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: flex-start;
      width: calc(100% - 40rpx);
      margin: 0 auto 24rpx;
      min-height: 110rpx;
      background-color: #fff;
      border-radius: 20rpx;
      padding: 24rpx;

      .label {
        color: #333;
        font-size: 28rpx;
        font-weight: 400;
        line-height: 36rpx;
        width: 40%;
      }
    }

    // .bar {
    //   transition: 0.2s;
    //   background-color: white;
    //   border-radius: 20rpx;
    //   margin-bottom: 24rpx;
    //   padding: 24rpx;

    //   .title {
    //     color: #333;
    //     font-weight: bold;
    //     font-size: 28rpx;
    //     margin-bottom: 20rpx;

    //     .cuIcon-right {
    //       float: right;
    //     }
    //   }

    //   .container_fold {
    //     padding: 24rpx;

    //     .formItem {
    //       display: flex;
    //       flex-direction: row;
    //       justify-content: space-between;
    //       align-items: flex-start;
    //       height: auto;

    //       .label {
    //         color: #333;
    //         font-size: 28rpx;
    //         font-weight: 400;
    //         line-height: 36rpx;
    //         width: 40%;
    //       }

    //       .content {
    //         text-align: right;
    //         width: 60%;

    //         .input {
    //           input {
    //             overflow: hidden !important;
    //             /*隐藏*/
    //             white-space: nowrap !important;
    //             /*不换行*/
    //             text-overflow: ellipsis !important;
    //             /* 超出部分省略号 */
    //           }
    //         }
    //       }
    //     }

    //     .fold {
    //       display: none;

    //       .container_people {
    //         display: flex;
    //         flex-flow: row wrap;
    //         align-content: flex-start;

    //         .peopleName {
    //           margin-bottom: 20rpx;
    //           text-align: center;
    //           line-height: 36rpx;
    //           color: white;
    //           flex: 0 0 calc((100% - 72rpx) / 4);
    //           background: rgba(52, 90, 199, 0.5);
    //           border-radius: 20rpx;
    //           padding: 12rpx 0;

    //           &:not(:nth-child(4n)) {
    //             margin-right: 24rpx;
    //           }
    //         }
    //       }
    //     }
    //   }
    // }

    .selecting {
      .view {
        display: none;
      }

      .fold {
        display: inherit !important;
      }
    }
  }

  .footer {
    height: 100rpx;
    background-color: white;
    box-shadow: 0 -10rpx 10rpx rgba(0, 0, 0, 0.2);
    position: fixed;
    bottom: 0;
    width: 100%;
    z-index: 9;

    .btn_submit {
      color: #fff;
      border-radius: 20rpx;
      background: $OVERALL_CONFIRM_BUTTON_COLOR;
      text-align: center;
      font-size: 28rpx;
      line-height: 80rpx;
      width: calc(100% - 40rpx);
      margin: 10rpx auto;
    }
  }
}
</style>
